package com.demo.websocketbarrage.service;


import com.demo.websocketbarrage.entity.PlayerSiteCommand;
import com.demo.websocketbarrage.entity.Site;
import com.sun.org.apache.xml.internal.security.Init;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Random;

@Service
public class GameService {
    final private Integer minX=0;
    final private Integer minY=0;
    final private Integer maxX=14;
    final private Integer maxY=14;

    /**
     * 解释执行 playerSiteCommand
     * @param gameSiteData
     * @param playerSiteCommand
     * @return
     */
    public  HashMap<String, Site> executePlayerSiteCommand(HashMap<String,Site> gameSiteData, PlayerSiteCommand playerSiteCommand){
        String playerName = playerSiteCommand.getName();
        String command = playerSiteCommand.getCommand();
        Site nowSite = gameSiteData.get(playerName);

        if (nowSite==null){//没有找到已有玩家数据
            return Initplayer(gameSiteData,playerName);
        }
        if ("offline".equals(command)){
            return playerOffline(gameSiteData,playerName);
        }

        gameSiteData.put(playerName,commondSetSite(nowSite,command));
        return gameSiteData;
    }

    /**
     * 玩家下线
     * @param gameSiteData
     * @param player
     * @return
     */
    public HashMap<String, Site> playerOffline(HashMap<String,Site> gameSiteData,String player){
        gameSiteData.remove(player);
        return gameSiteData;
    }

    /**
     * 玩家生成
     * @param gameSiteData
     * @param player
     * @return
     */
    public  HashMap<String, Site> Initplayer(HashMap<String,Site> gameSiteData,String player){
        Site site = new Site(new Random().nextInt(maxX + 1), new Random().nextInt(maxY + 1));
        gameSiteData.put(player,site);
        return gameSiteData;
    }

    public Site commondSetSite(Site site,String inputCommand){ //执行位置改变
        if ("up".equals(inputCommand)){
            site.checkUpAndTurn(minY);
        }else if ("down".equals(inputCommand)){
            site.checkDownAndTurn(maxY);
        }else if ("left".equals(inputCommand)){
            site.checkLeftAndTurn(minX);
        }else if ("right".equals(inputCommand)){
            site.checkRightAndTurn(maxX);
        }
        return site;
    }




}
